var debug = require('debug')('westmarket')
var koa = require('koa')
var app = koa()

// 错误处理
require('koa-onerror')(app)

// 错误处理
app.use(function *(next) {
    var ctx = this
    var _render = function *(status, message, dir) {
        if(ctx.is('application/javascript', 'application/json')){
            ctx.body = {
                code: status,
                message: message
            }
        }else{
            yield ctx.render(dir, {
                message: message,
                code: status
            })
        }
    }

    try{
        yield next
    }catch(err){
        console.error(err.stack)
        return yield _render(500, '服务器繁忙', 'error/500')
    }

    var status = ctx.status || 500

    if(404 === status){
        return yield _render(404, '你要的页面没有找到', 'error/404')
    }else if(403 === status){
        return yield _render(403, '服务器拒绝执行', 'error/403')
    }else if(400 === status){
        return yield _render(400, '无效的请求', 'error/400')
    }else if(500 === status){
        return yield _render(500, '服务器繁忙', 'error/500')
    }else{
        return false
    }

})

//log记录
app.use(require('koa-logger')())

//配置文件
var config = require('./config')
app.use(function *(next) {
    if (!this.config) {
        this.config = config
    }
    yield next
})

// session
app.keys = ['secret', 'cento thanatos']
app.use(require('koa-session')(app))

// 模板引擎
var render = require('koa-views')
app.use(render(config.dir.views, {default: "jade"}))

//post body 解析
var bodyparser = require('koa-bodyparser')
app.use(bodyparser({
    onerror: function (err, ctx) {
        ctx.throw('body parse error', 403)
    }
}))

//mysql
var wrapper = require('co-mysql')
var mysql = require('mysql')
var pool = mysql.createPool(config.mysql)
app.use(function *(next) {
    this.db = wrapper(pool).query
    yield next
})

//静态文件
var staticCache = require('koa-static-cache');
app.use(staticCache(config.dir.static, {
    //maxAge: 604800000, // 7 days
    maxAge: 0,
    gzip: true
}))

//静态文件加载
var combo = require("koa-combo")
app.use(combo([config.dir.static]))

// 权限拦截
//app.use(function *(next) {
//    if(this.request.url.startsWith('/user') && !this.session.user || !this.session.user.id)
//        this.status = 404
//    else
//        yield next
//})

//路由
app.use(require('koa-router')(app))
require('./router/universal')(app)
require('./router/user')(app)
require('./router/recipe')(app)
require('./router/menu')(app)

app.listen(config.port)
console.log('listening on port %s', config.port)

module.exports = app

